package com.spz.demo.singleboot.shiro.matcher;

import com.spz.demo.singleboot.entity.User;
import com.spz.demo.singleboot.shiro.token.UserAuthenticationToken;
import com.spz.demo.singleboot.util.StringUtil;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;

/**
 * 改写原有的密码匹配器
 * 用于账号密码登录时的账密匹配
 */
public class PasswordCredentialsMatcher implements CredentialsMatcher {
    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        //账号密码登录，则token应该是自定义的 AccountPasswordAuthenticationToken
        if(token instanceof UserAuthenticationToken){
            //这里检查账号和密码是否匹配
            //token是登录接口那里获取的，info是通过account获取到数据里的信息
            //密码需要进行md5处理，因为数据库存储的密码为密文
            if(info.getPrincipals().getPrimaryPrincipal() instanceof User){
                User user = (User)info.getPrincipals().getPrimaryPrincipal();
                if(token.getPrincipal().equals(user.getAccount()) &&
                        StringUtil.md5((String) token.getCredentials()).equals(user.getPassword())){
                    return true;
                }
            }

        }
        return false;
    }
}
